<template>
  <div class="exam-container">
    <h1>考试管理</h1>
    
    <div class="user-info">
      <p>欢迎，{{ userProfile.fullName }}老师</p>
      <router-link to="/teacher/dashboard">返回Dashboard</router-link>
    </div>

    <!-- 发布考试表单 -->
    <div class="publish-exam-section">
      <h2>发布新考试</h2>
      <form @submit.prevent="publishExam" class="exam-form">
        <div class="form-group">
          <label for="examName">考试名称:</label>
          <input type="text" id="examName" v-model="examForm.name" required />
        </div>
        
        <div class="form-group">
          <label for="classId">班级:</label>
          <select id="classId" v-model="examForm.classId" @change="onClassChange" required>
            <option value="">请选择班级</option>
            <option v-for="classItem in teachingClasses" :key="classItem.id" :value="classItem.id">
              {{ classItem.className }}
            </option>
          </select>
        </div>
        
        <div class="form-group">
          <label for="subjectId">学科:</label>
          <select id="subjectId" v-model="examForm.subjectId" required>
            <option value="">请选择学科</option>
            <option v-for="subject in availableSubjects" :key="subject.subjectId" :value="subject.subjectId">
              {{ subject.subjectName }}
            </option>
          </select>
        </div>
        
        <div class="form-group">
          <label for="examDate">考试日期:</label>
          <input type="date" id="examDate" v-model="examForm.examDate" required />
        </div>
        
        <button type="submit" class="submit-btn">发布考试</button>
      </form>
    </div>

    <!-- 考试列表 -->
    <div class="exam-list-section">
      <h2>考试列表</h2>
      <div class="class-selector">
        <label for="selectedClass">选择班级:</label>
        <select id="selectedClass" v-model="selectedClassId" @change="loadExamList">
          <option value="">请选择班级</option>
          <option v-for="classItem in teachingClasses" :key="classItem.id" :value="classItem.id">
            {{ classItem.className }}
          </option>
        </select>
      </div>
      
      <div v-if="loading" class="loading">加载中...</div>
      <div v-else-if="examList.length > 0" class="exam-list">
        <div v-for="exam in examList" :key="exam.id" class="exam-card">
          <h3>{{ exam.name }}</h3>
          <p>考试日期: {{ formatDate(exam.examDate) }}</p>
          <p>学科: {{ getSubjectName(exam.subjectId) }}</p>
          <div class="exam-actions">
            <button @click="viewScores(exam)" class="view-scores-btn">查看成绩</button>
          </div>
        </div>
      </div>
      <div v-else class="no-exams">
        <p>暂无考试信息</p>
      </div>
    </div>

    <!-- 录入成绩模态框 -->
    <div v-if="showScoreModal" class="modal-overlay" @click="closeScoreModal">
      <div class="modal-content" @click.stop>
        <h2>录入成绩 - {{ selectedExam.name }}</h2>
        <div class="score-form">
          <div class="score-table-container">
            <table class="score-table">
              <thead>
                <tr>
                  <th>学号</th>
                  <th>姓名</th>
                  <th>成绩</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="student in studentsInClass" :key="student.id">
                  <td>{{ student.studentNumber }}</td>
                  <td>{{ student.fullName }}</td>
                  <td>
                    <input 
                      type="number" 
                      :id="'score-' + student.id" 
                      v-model="studentScores[student.id]" 
                      min="0" 
                      max="100" 
                      step="0.5"
                      placeholder="请输入成绩"
                    />
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="modal-actions">
            <button @click="submitScores" class="submit-btn">提交成绩</button>
            <button @click="closeScoreModal" class="cancel-btn">取消</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 查看成绩模态框 -->
    <div v-if="showViewScoresModal" class="modal-overlay" @click="closeViewScoresModal">
      <div class="modal-content" @click.stop>
        <h2>考试成绩 - {{ selectedExam.name }}</h2>
        <div class="score-table-container">
          <table class="score-table">
            <thead>
              <tr>
                <th>学号</th>
                <th>姓名</th>
                <th>成绩</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="score in examScores" :key="score.id">
                <td>{{ score.studentNumber }}</td>
                <td>{{ score.studentName }}</td>
                <td>{{ score.score }}</td>
                <td>
                  <button @click="editScore(score)" class="edit-btn">修改</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="modal-actions">
          <button @click="closeViewScoresModal" class="cancel-btn">关闭</button>
        </div>
      </div>
    </div>

    <!-- 修改成绩模态框 -->
    <div v-if="showEditScoreModal" class="modal-overlay" @click="closeEditScoreModal">
      <div class="modal-content" @click.stop>
        <h2>修改成绩</h2>
        <div class="edit-score-form">
          <p>学生: {{ currentScore?.studentName }}</p>
          <p>原成绩: {{ currentScore?.score }}</p>
          <div class="form-group">
            <label for="newScore">新成绩:</label>
            <input 
              type="number" 
              id="newScore" 
              v-model="newScore" 
              min="0" 
              max="100" 
              step="0.5"
              placeholder="请输入新成绩"
            />
          </div>
          <div class="modal-actions">
            <button @click="updateScore" class="submit-btn">确认修改</button>
            <button @click="closeEditScoreModal" class="cancel-btn">取消</button>
          </div>
        </div>
      </div>
    </div>

    <div v-if="successMessage" class="success-message">
      {{ successMessage }}
    </div>
    
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';

export default {
  name: 'ExamManagement',
  setup() {
    const router = useRouter();
    const userProfile = ref({});
    const teachingClasses = ref([]);
    const examList = ref([]);
    const selectedClassId = ref('');
    const loading = ref(false);
    const successMessage = ref('');
    const errorMessage = ref('');
    
    // 考试表单
    const examForm = ref({
      name: '',
      classId: '',
      subjectId: '',
      examDate: ''
    });
    
    // 学科相关
    const availableSubjects = ref([]);
    
    // 成绩相关
    const showScoreModal = ref(false);
    const showViewScoresModal = ref(false);
    const showEditScoreModal = ref(false);
    const selectedExam = ref({});
    const studentsInClass = ref([]);
    const studentScores = ref({});
    const examScores = ref([]);
    const currentScore = ref(null);
    const newScore = ref('');
    
    // 存储班级学生信息
    const classStudents = ref({});
    
    // 获取用户信息
    const loadUserProfile = async () => {
      try {
        const response = await fetch('/user/profile', {
          method: 'GET',
          credentials: 'include'
        });
        
        const result = await response.json();
        if (result.code === 1) {
          userProfile.value = result.data;
        } else {
          errorMessage.value = result.msg || '获取用户信息失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };
    
    // 获取教师授课班级
    const loadTeachingClasses = async () => {
      try {
        const response = await fetch('/teacher/exam/classes', {
          method: 'GET',
          credentials: 'include'
        });
        
        const result = await response.json();
        if (result.code === 1) {
          teachingClasses.value = result.data || [];
        } else {
          errorMessage.value = result.msg || '获取班级列表失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };
    
    // 班级改变时更新可选学科
    const onClassChange = () => {
      examForm.value.subjectId = '';
      updateAvailableSubjects();
    };
    
    // 更新可选学科列表
    const updateAvailableSubjects = () => {
      if (examForm.value.classId && userProfile.value.teachingCourses) {
        availableSubjects.value = userProfile.value.teachingCourses.filter(
          course => course.classId === examForm.value.classId
        );
      } else {
        availableSubjects.value = [];
      }
    };
    
    // 发布考试
    const publishExam = async () => {
      if (!examForm.value.name || !examForm.value.classId || !examForm.value.subjectId || !examForm.value.examDate) {
        errorMessage.value = '请填写完整的考试信息';
        return;
      }
      
      try {
        const response = await fetch('/teacher/exam/publish', {
          method: 'POST',
          credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(examForm.value)
        });
        
        const result = await response.json();
        if (result.code === 1) {
          successMessage.value = '考试发布成功';
          examForm.value = { name: '', classId: '', subjectId: '', examDate: '' };
          // 重新加载考试列表
          if (selectedClassId.value) {
            loadExamList();
          }
        } else {
          errorMessage.value = result.msg || '考试发布失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };
    
    // 加载考试列表
    const loadExamList = async () => {
      if (!selectedClassId.value) {
        examList.value = [];
        return;
      }
      
      try {
        loading.value = true;
        const response = await fetch(`/teacher/exam/list/${selectedClassId.value}`, {
          method: 'GET',
          credentials: 'include'
        });
        
        const result = await response.json();
        if (result.code === 1) {
          examList.value = result.data || [];
        } else {
          errorMessage.value = result.msg || '获取考试列表失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      } finally {
        loading.value = false;
      }
    };
    
    // 获取班级学生列表
    const loadClassStudents = async (classId) => {
      // 如果已经加载过该班级的学生信息，直接返回
      if (classStudents.value[classId]) {
        return classStudents.value[classId];
      }
      
      try {
        const response = await fetch('/teacher/chat/contacts', {
          method: 'GET',
          credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          params: { classId: classId }
        });
        
        const result = await response.json();
        if (result.code === 1) {
          // 过滤出学生信息
          const students = result.data.filter(contact => contact.userType === '2'); // 学生的userType是'2'
          classStudents.value[classId] = students;
          return students;
        } else {
          errorMessage.value = result.msg || '获取学生列表失败';
          return [];
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
        return [];
      }
    };
    
    // 选择考试进行成绩录入
    const selectExamForScoring = async (exam) => {
      selectedExam.value = exam;
      
      // 获取班级学生列表
      try {
        const students = await loadClassStudents(exam.classId);
        if (students) {
          studentsInClass.value = students.map(student => ({
            id: student.userId,
            studentNumber: student.studentNumber || '未知学号',
            fullName: student.fullName || '未知姓名'
          }));
          
          // 初始化成绩对象
          studentScores.value = {};
          studentsInClass.value.forEach(student => {
            studentScores.value[student.id] = '';
          });
          showScoreModal.value = true;
        } else {
          errorMessage.value = '获取学生列表失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };
    
    // 关闭成绩录入模态框
    const closeScoreModal = () => {
      showScoreModal.value = false;
      selectedExam.value = {};
      studentsInClass.value = [];
      studentScores.value = {};
    };
    
    // 提交成绩
    const submitScores = async () => {
      // 验证成绩
      const scores = [];
      let valid = true;
      
      for (const studentId in studentScores.value) {
        const scoreValue = studentScores.value[studentId];
        if (scoreValue === '' || scoreValue === null || scoreValue === undefined) {
          errorMessage.value = '请填写所有学生的成绩';
          valid = false;
          break;
        }
        
        if (scoreValue < 0 || scoreValue > 100) {
          errorMessage.value = '成绩应在0-100之间';
          valid = false;
          break;
        }
        
        scores.push({
          studentId: parseInt(studentId),
          score: parseFloat(scoreValue)
        });
      }
      
      if (!valid) {
        return;
      }
      
      try {
        const response = await fetch(`/teacher/exam/scores/${selectedExam.value.id}`, {
          method: 'POST',
          credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(scores)
        });
        
        const result = await response.json();
        if (result.code === 1) {
          successMessage.value = '成绩录入成功';
          closeScoreModal();
        } else {
          errorMessage.value = result.msg || '成绩录入失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };
    
    // 查看成绩
    const viewScores = async (exam) => {
      selectedExam.value = exam;
      
      try {
        // 获取考试成绩
        const response = await fetch(`/teacher/exam/scores/${exam.id}`, {
          method: 'GET',
          credentials: 'include'
        });
        
        const result = await response.json();
        if (result.code === 1) {
          examScores.value = result.data || [];
          showViewScoresModal.value = true;
        } else {
          errorMessage.value = result.msg || '获取成绩列表失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };
    
    // 关闭查看成绩模态框
    const closeViewScoresModal = () => {
      showViewScoresModal.value = false;
      selectedExam.value = {};
      examScores.value = [];
    };
    
    // 编辑成绩
    const editScore = (score) => {
      currentScore.value = {
        ...score,
        studentName: score.studentName
      };
      newScore.value = score.score;
      showEditScoreModal.value = true;
    };
    
    // 关闭编辑成绩模态框
    const closeEditScoreModal = () => {
      showEditScoreModal.value = false;
      currentScore.value = null;
      newScore.value = '';
    };
    
    // 更新成绩
    const updateScore = async () => {
      if (newScore.value === '' || newScore.value < 0 || newScore.value > 100) {
        errorMessage.value = '请输入有效的成绩(0-100)';
        return;
      }
      
      try {
        const response = await fetch(`/teacher/exam/scores/${currentScore.value.id}?newScore=${newScore.value}`, {
          method: 'PUT',
          credentials: 'include'
        });
        
        const result = await response.json();
        if (result.code === 1) {
          successMessage.value = '成绩更新成功';
          closeEditScoreModal();
          // 重新加载成绩列表
          viewScores(selectedExam.value);
        } else {
          errorMessage.value = result.msg || '成绩更新失败';
        }
      } catch (err) {
        errorMessage.value = '网络错误，请稍后重试';
      }
    };
    
    // 根据学生ID获取学生信息
    const getStudentInfoById = (studentId) => {
      // 在examScores中查找对应的学生信息
      for (let score of examScores.value) {
        if (score.studentId === studentId) {
          return {
            studentNumber: score.studentNumber,
            fullName: score.studentName
          };
        }
      }
      return null;
    };
    
    // 根据学科ID获取学科名称
    const getSubjectName = (subjectId) => {
      if (userProfile.value.teachingCourses) {
        const subject = userProfile.value.teachingCourses.find(course => course.subjectId === subjectId);
        return subject ? subject.subjectName : '未知学科';
      }
      return '未知学科';
    };
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      return dateString;
    };
    
    // 清除消息
    const clearMessages = () => {
      successMessage.value = '';
      errorMessage.value = '';
    };
    
    // 监听消息变化，3秒后自动清除
    const watchMessages = () => {
      if (successMessage.value || errorMessage.value) {
        setTimeout(() => {
          clearMessages();
        }, 3000);
      }
    };
    
    onMounted(() => {
      loadUserProfile().then(() => {
        loadTeachingClasses();
      });
    });
    
    return {
      userProfile,
      teachingClasses,
      examList,
      selectedClassId,
      loading,
      successMessage,
      errorMessage,
      examForm,
      availableSubjects,
      showScoreModal,
      showViewScoresModal,
      showEditScoreModal,
      selectedExam,
      studentsInClass,
      studentScores,
      examScores,
      currentScore,
      newScore,
      loadExamList,
      publishExam,
      selectExamForScoring,
      closeScoreModal,
      submitScores,
      viewScores,
      closeViewScoresModal,
      editScore,
      closeEditScoreModal,
      updateScore,
      getStudentInfoById,
      getSubjectName,
      formatDate,
      onClassChange
    };
  }
};
</script>

<style scoped>
.exam-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.exam-container h1 {
  text-align: center;
  color: #333;
}

.user-info {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 5px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info a {
  color: #409EFF;
  text-decoration: none;
}

.user-info a:hover {
  text-decoration: underline;
}

.publish-exam-section {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 20px;
}

.publish-exam-section h2 {
  margin-top: 0;
  color: #333;
}

.exam-form .form-group {
  margin-bottom: 15px;
}

.exam-form label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.exam-form input,
.exam-form select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.submit-btn {
  padding: 10px 20px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.submit-btn:hover {
  background-color: #337ecc;
}

.exam-list-section {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 20px;
}

.exam-list-section h2 {
  margin-top: 0;
  color: #333;
}

.class-selector {
  margin-bottom: 20px;
}

.class-selector label {
  margin-right: 10px;
  font-weight: bold;
}

.exam-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.exam-card {
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 15px;
}

.exam-card h3 {
  margin-top: 0;
  color: #333;
}

.exam-card p {
  margin: 10px 0;
  color: #666;
}

.exam-actions {
  margin-top: 15px;
  display: flex;
  gap: 10px;
}

.score-btn,
.view-scores-btn,
.edit-btn {
  padding: 5px 10px;
  background-color: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.edit-btn {
  background-color: #e6a23c;
}

.edit-btn:hover {
  background-color: #d69230;
}

.view-scores-btn {
  background-color: #67c23a;
}

.view-scores-btn:hover {
  background-color: #58a832;
}

.no-exams {
  text-align: center;
  padding: 20px;
  color: #999;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 5px;
  padding: 20px;
  max-width: 800px;
  max-height: 80vh;
  overflow-y: auto;
  width: 90%;
}

.modal-content h2 {
  margin-top: 0;
  color: #333;
}

.score-table-container {
  overflow-x: auto;
  margin-bottom: 20px;
}

.score-table {
  width: 100%;
  border-collapse: collapse;
}

.score-table th,
.score-table td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: left;
}

.score-table th {
  background-color: #f5f5f5;
  font-weight: bold;
}

.score-table input {
  width: 80px;
  padding: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.cancel-btn {
  padding: 10px 20px;
  background-color: #909399;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.cancel-btn:hover {
  background-color: #7a7c82;
}

.edit-score-form .form-group {
  margin-bottom: 15px;
}

.edit-score-form label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.edit-score-form input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.success-message {
  background-color: #f0f9eb;
  color: #67c23a;
  padding: 15px;
  border-radius: 5px;
  margin-top: 20px;
}

.error-message {
  background-color: #f8d7da;
  color: #f56c6c;
  padding: 15px;
  border-radius: 5px;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .exam-list {
    grid-template-columns: 1fr;
  }
  
  .exam-actions {
    flex-direction: column;
  }
  
  .modal-content {
    width: 95%;
    padding: 15px;
  }
}
</style>